﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Media3D;
using Antlr.Runtime;

namespace GeometryViz3D.Model
{
    internal class ModelBuilder : IModelBuilder
    {
        G3DModel m_model = new G3DModel();

        public ModelBuilder()
        {
        }

        public static G3DModel BuildFromString(string str)
        {
            ICharStream input = new ANTLRStringStream(str);
            return Build(input);
        }

        public static G3DModel BuildFromFile(string name)
        {
            ICharStream input = new ANTLRFileStream(name);
            var model = Build(input);
            model.FileName = name;

            return model;
        }

        public G3DModel Model
        {
            get { return m_model; }
        }

        public void AddPoint(string label, string x, string y, string z)
        {
            double xx, yy, zz;

            if (!double.TryParse(x, out xx))
            {
                // report
                return;
            }

            if (!double.TryParse(y, out yy))
            {
                // report
                return;
            }

            if (!double.TryParse(z, out zz))
            {
                // report
                return;
            }

            m_model.AddPoint(label, new Point3D(xx, yy, zz));
        }

        public void AddLine(string label, string p1, string p2, string color)
        {
            m_model.AddLine(label, p1, p2, color);
        }

        private static G3DModel Build(ICharStream input)
        {
            G3DLexer lexer = new G3DLexer(input);

            CommonTokenStream tokens = new CommonTokenStream(lexer);
            G3DParser parser = new G3DParser(tokens);

            ModelBuilder builder = new ModelBuilder();

            parser.ModelBuilder = builder;

            parser.model();

            // Clear the dirty flag because the model was just loaded from a file.
            builder.Model.IsDirty = false;

            return builder.Model;
        }
    }
}
